import tkinter as tk
from tkinter import ttk
from queue import Queue
from threading import Thread
from datetime import datetime
from ..utils.logger import AppLogger


class LogPanel:
    def __init__(self, parent):
        self.parent = parent
        self.log_queue = Queue()
        self._setup_ui()
        self._start_log_monitor()

    def _setup_ui(self):
        """初始化日志面板界面"""
        self.frame = ttk.Frame(self.parent, padding=10)

        # 日志显示区域
        self.log_text = tk.Text(
            self.frame,
            wrap=tk.WORD,
            state=tk.DISABLED,
            font=("Consolas", 10),
            bg="#2d2d2d",
            fg="#ffffff",
            insertbackground="white",
            selectbackground="#3e3e3e"
        )

        # 滚动条
        scrollbar = ttk.Scrollbar(
            self.frame,
            orient=tk.VERTICAL,
            command=self.log_text.yview
        )
        self.log_text.configure(yscrollcommand=scrollbar.set)

        # 控制按钮
        btn_frame = ttk.Frame(self.frame)
        clear_btn = ttk.Button(
            btn_frame,
            text="清空日志",
            command=self.clear_logs
        )
        copy_btn = ttk.Button(
            btn_frame,
            text="复制日志",
            command=self.copy_logs
        )

        # 布局
        self.log_text.grid(row=0, column=0, sticky="nsew")
        scrollbar.grid(row=0, column=1, sticky="ns")
        btn_frame.grid(row=1, column=0, columnspan=2, pady=5)
        clear_btn.pack(side=tk.LEFT, padx=5)
        copy_btn.pack(side=tk.LEFT, padx=5)

        # 配置网格布局
        self.frame.grid_rowconfigure(0, weight=1)
        self.frame.grid_columnconfigure(0, weight=1)

        # 绑定右键菜单
        self._setup_context_menu()

    def _setup_context_menu(self):
        """设置右键菜单"""
        self.context_menu = tk.Menu(self.log_text, tearoff=0)
        self.context_menu.add_command(
            label="复制",
            command=self.copy_logs
        )
        self.context_menu.add_command(
            label="清空",
            command=self.clear_logs
        )
        self.context_menu.add_separator()
        self.context_menu.add_command(
            label="搜索",
            command=self.show_search_box
        )

        self.log_text.bind(
            "<Button-3>",
            lambda e: self.context_menu.tk_popup(e.x_root, e.y_root)
        )

    def _start_log_monitor(self):
        """启动日志监控线程"""

        def monitor():
            while True:
                try:
                    msg = self.log_queue.get()
                    if msg is None:
                        break

                    self._append_log(msg)
                except Exception as e:
                    print(f"Log monitor error: {str(e)}")

        self.monitor_thread = Thread(target=monitor, daemon=True)
        self.monitor_thread.start()

    def _append_log(self, message):
        """追加日志到显示区域"""
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        formatted_msg = f"[{timestamp}] {message}\n"

        self.log_text.configure(state=tk.NORMAL)
        self.log_text.insert(tk.END, formatted_msg)
        self.log_text.configure(state=tk.DISABLED)

        # 自动滚动到底部
        self.log_text.yview_moveto(1.0)

    def clear_logs(self):
        """清空日志"""
        self.log_text.configure(state=tk.NORMAL)
        self.log_text.delete(1.0, tk.END)
        self.log_text.configure(state=tk.DISABLED)

    def copy_logs(self):
        """复制日志内容"""
        self.parent.clipboard_clear()
        self.parent.clipboard_append(
            self.log_text.get(1.0, tk.END)
        )

    def show_search_box(self):
        """显示搜索框"""
        search_window = tk.Toplevel(self.parent)
        search_window.title("搜索日志")

        search_frame = ttk.Frame(search_window, padding=10)
        search_frame.pack(fill=tk.BOTH, expand=True)

        search_entry = ttk.Entry(search_frame)
        search_entry.pack(fill=tk.X, pady=5)

        result_text = tk.Text(
            search_frame,
            wrap=tk.WORD,
            state=tk.DISABLED,
            font=("Consolas", 10),
            bg="#2d2d2d",
            fg="#ffffff"
        )
        result_text.pack(fill=tk.BOTH, expand=True)

        def perform_search():
            query = search_entry.get().strip()
            if not query:
                return

            result_text.configure(state=tk.NORMAL)
            result_text.delete(1.0, tk.END)

            log_content = self.log_text.get(1.0, tk.END)
            lines = log_content.split("\n")

            for line in lines:
                if query.lower() in line.lower():
                    result_text.insert(tk.END, line + "\n")

            result_text.configure(state=tk.DISABLED)

        search_btn = ttk.Button(
            search_frame,
            text="搜索",
            command=perform_search
        )
        search_btn.pack(pady=5)

    def log_message(self, level, message):
        """记录日志消息"""
        self.log_queue.put(f"[{level.upper()}] {message}")

    def stop(self):
        """停止日志监控"""
        self.log_queue.put(None)
        self.monitor_thread.join(timeout=1)